package com.stox.ui.javafx.core.application;

import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.stox.dto.intf.Application;

@Component("applicationPane")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ApplicationPane extends BorderPane {

	private Label nameLabel;
	
	private Label descriptionLabel;
	
	private final Application application;
	
	@Autowired
	private ApplicationContext applicationContext;
	
	private EventHandler<MouseEvent> onDragDetectedEventHandler = new EventHandler<MouseEvent>() {
		@Override
		public void handle(MouseEvent event) {
			Dragboard db = startDragAndDrop(TransferMode.ANY);
			ClipboardContent content = new ClipboardContent();
			content.putString(application.getApplicationClassName());
			db.setContent(content);
			SnapshotParameters snapshotParameters = new SnapshotParameters();
			snapshotParameters.setFill(Color.TRANSPARENT);
			db.setDragView(snapshot(snapshotParameters, null));
			
			ApplicationPopOver applicationPopOver = applicationContext.getBean(ApplicationPopOver.class);
			applicationPopOver.hide();
			event.consume();
		}
	};
	
	public ApplicationPane(Application application) {
		this.application = application;
		setId("apps-pane");
		addNameLabel();
		addDescriptionLabel();
		setOnDragDetected(onDragDetectedEventHandler);
	}
	
	private void addDescriptionLabel(){
		descriptionLabel = new Label(application.getDescription());
		descriptionLabel.setId("apps-description-label");
		descriptionLabel.setMaxWidth(500);
		descriptionLabel.setWrapText(true);
		setCenter(createScrollPane(descriptionLabel));
	}
	
	private ScrollPane createScrollPane(Node node){
		ScrollPane scrollPane = new ScrollPane(node);
		scrollPane.setId("apps-scroll-pane");
		scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
		scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
		return scrollPane;
	}
	
	private void addNameLabel(){
		nameLabel = new Label(application.getName());
		nameLabel.setId("apps-name-label");
		setTop(nameLabel);
	}
	
	public Application getApplication() {
		return application;
	}
	
}
